//
//
//
//
//  Created by lbxia on 15/10/21.
//  Copyright © 2015年 lbxia. All rights reserved.
//

#import "SubLBXScanViewController.h"
#import "MyQRViewController.h"
#import "ScanResultViewController.h"
#import "LBXScanResult.h"
#import "LBXScanWrapper.h"
//#import "WebviewDetailInfoViewController.h"
//#import "MyCarInfoListViewController.h"
@interface SubLBXScanViewController ()<LQRequestApiDelegate>
@property (strong, nonatomic) IBOutlet UIButton *backButton;

@end

@implementation SubLBXScanViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self adaptiveViewLayout:self.view];
    self.shareApi=[LQRequestApi sharedInstance];
    self.shareApi.delegate=self;
    self.view.backgroundColor = [UIColor blackColor];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    
    if (_isQQSimulator) {
        
         [self drawBottomItems];
        [self drawTitle];
         [self.view bringSubviewToFront:_topTitle];
        
    }
    else{
        _topTitle.hidden = YES;
       
    }
    [self.view bringSubviewToFront:self.backButton];
    
   
}

#pragma   mark  返回======================================
- (IBAction)backClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark  调整自适应布局
- (void) adaptiveViewLayout:(UIView *)viewLayout{
    //视图自适应布局
    for (UIView *view in viewLayout.subviews) {
        view.frame = flexibleFrame(view.frame, NO);
        if ([view isKindOfClass:[UITextField class]]) {
            UITextField *viewField = (UITextField *)view;
            CGFloat fontSize = viewField.font.pointSize;
            viewField.font = [UIFont systemFontOfSize:fontSize*VerticalTexeRatio()];
        }else if ([view isKindOfClass:[UILabel class]]){
            UILabel *viewLabel = (UILabel *)view;
            CGFloat fontSize = viewLabel.font.pointSize;
            viewLabel.font = [UIFont systemFontOfSize:fontSize*VerticalTexeRatio()];
        }else if ([view isKindOfClass:[UIButton class]]){
            UIButton *viewButton = (UIButton *)view;
            CGFloat fontSize = viewButton.titleLabel.font.pointSize;
            viewButton.titleLabel.font = [UIFont systemFontOfSize:fontSize*VerticalTexeRatio()];
        }
        
    }
}

//绘制扫描区域
- (void)drawTitle
{
    if (!_topTitle)
    {
        
        
        self.topTitle = [[UILabel alloc]init];
        _topTitle.bounds = CGRectMake(0, 0+64, 145, 60);
        _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 50);
        
        //3.5inch iphone
        if ([UIScreen mainScreen].bounds.size.height <= 568 )
        {
            _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 38);
            _topTitle.font = [UIFont systemFontOfSize:14];
        }
        
        
        _topTitle.textAlignment = NSTextAlignmentCenter;
        _topTitle.numberOfLines = 0;
        _topTitle.text = @"将取景框对准二维码即可自动扫描";
        _topTitle.textColor = [UIColor whiteColor];
        [self.view addSubview:_topTitle];
    }
    
    
}

- (void)drawBottomItems
{
    if (_bottomItemsView) {
        
        return;
    }
    
    self.bottomItemsView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.frame)-164-64,
                                                                      CGRectGetWidth(self.view.frame), 100)];
    
    _bottomItemsView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    
    [self.view addSubview:_bottomItemsView];
    
    CGSize size = CGSizeMake(65, 87);
    self.btnFlash = [[UIButton alloc]init];
    _btnFlash.bounds = CGRectMake(0, 0+64, size.width, size.height);
    _btnFlash.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)/2, (CGRectGetHeight(_bottomItemsView.frame)-64)/2);
     [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
    [_btnFlash addTarget:self action:@selector(openOrCloseFlash) forControlEvents:UIControlEventTouchUpInside];
    
    self.btnPhoto = [[UIButton alloc]init];
    _btnPhoto.bounds = _btnFlash.bounds;
    _btnPhoto.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame)/4, (CGRectGetHeight(_bottomItemsView.frame)-64)/2);
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_nor"] forState:UIControlStateNormal];
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_down"] forState:UIControlStateHighlighted];
    [_btnPhoto addTarget:self action:@selector(openPhoto) forControlEvents:UIControlEventTouchUpInside];
    
    self.btnMyQR = [[UIButton alloc]init];
    _btnMyQR.bounds = _btnFlash.bounds;
    _btnMyQR.center = CGPointMake(CGRectGetWidth(_bottomItemsView.frame) * 3/4, (CGRectGetHeight(_bottomItemsView.frame)-64)/2);
    [_btnMyQR setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_myqrcode_nor"] forState:UIControlStateNormal];
    [_btnMyQR setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_myqrcode_down"] forState:UIControlStateHighlighted];
    [_btnMyQR addTarget:self action:@selector(myQRCode) forControlEvents:UIControlEventTouchUpInside];
    
    [_bottomItemsView addSubview:_btnFlash];
    [_bottomItemsView addSubview:_btnPhoto];
    [_bottomItemsView addSubview:_btnMyQR];   
    
}

- (void)showError:(NSString*)str
{
    [LBXAlertAction showAlertWithTitle:@"提示" msg:str chooseBlock:nil buttonsStatement:@"知道了",nil];
}



- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array
{
    
    if (array.count < 1)
    {
        [self popAlertMsgWithScanResult:nil];
     
        return;
    }
    
    //经测试，可以同时识别2个二维码，不能同时识别二维码和条形码
    for (LBXScanResult *result in array) {
        
//        NSLog(@"scanResult:%@",result.strScanned);
        if([result.strScanned rangeOfString:@"http://"].location !=NSNotFound || [result.strScanned rangeOfString:@"https://"].location !=NSNotFound)//_roaldSearchText
        {
            
            [self dismissViewControllerAnimated:NO completion:^{
//                UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTabStoryboard" bundle:nil];
//                WebviewDetailInfoViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WebviewDetailInfo"];
//                page.objectType = @"车骑士";
//                page.titleName = result.strScanned;
//                [self.navigationController   pushViewController:page animated:YES];
            }];
        }
        else
        {
            NSArray *scanResult = [result.strScanned componentsSeparatedByString:@" "];
            //        NSLog(@"===%@",scanResult);
            if (scanResult.count > 6) {
                NSString *codeStr =scanResult[4];
                if ([codeStr isEqualToString:@"8989"]) {
                    // 扫描二维码获取红包
                    [self getRedenveByQRCode:result.strScanned];
                }else if ([codeStr isEqualToString:@"8099"]){
                    // 扫描二维码获取代金卷
                    [self getCouponByQRCode:result.strScanned];
                }else if ([codeStr isEqualToString:@"8080"]){
                    // 扫描二维码激活会员卡
                    [self getMemberCardByQRCode:result.strScanned];
                }
            }

        }
        
    }
    
    LBXScanResult *scanResult = array[0];
    
    NSString*strResult = scanResult.strScanned;
    
    self.scanImage = scanResult.imgScanned;
    
    if (!strResult) {
        
        [self popAlertMsgWithScanResult:nil];
        
        return;
    }
    
    //震动提醒
    [LBXScanWrapper systemVibrate];
    //声音提醒
    [LBXScanWrapper systemSound];
    
    
    //[self popAlertMsgWithScanResult:strResult];
    
//    [self showNextVCWithScanResult:scanResult];
   
}

- (void)popAlertMsgWithScanResult:(NSString*)strResult
{
    if (!strResult) {
        
        strResult = @"识别失败";
    }
    
    __weak __typeof(self) weakSelf = self;
    [LBXAlertAction showAlertWithTitle:@"扫码内容" msg:strResult chooseBlock:^(NSInteger buttonIdx) {
        
        //点击完，继续扫码
        [weakSelf reStartDevice];
    } buttonsStatement:@"知道了",nil];
}

- (void)showNextVCWithScanResult:(LBXScanResult*)strResult
{
    ScanResultViewController *vc = [ScanResultViewController new];
    vc.imgScan = strResult.imgScanned;
    
    vc.strScan = strResult.strScanned;
    
    vc.strCodeType = strResult.strBarCodeType;
    
    [self.navigationController  pushViewController:vc animated:YES];
}


#pragma mark -底部功能项
//打开相册
- (void)openPhoto
{
    if ([LBXScanWrapper isGetPhotoPermission])
        [self openLocalPhoto];
    else
    {
        [self showError:@"      请到设置->隐私中开启本程序相册权限     "];
    }
}

//开关闪光灯
- (void)openOrCloseFlash
{
    
    [super openOrCloseFlash];
   
    
    if (self.isOpenFlash)
    {
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_down"] forState:UIControlStateNormal];
    }
    else
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
}


#pragma mark -底部功能项


- (void)myQRCode
{
    MyQRViewController *vc = [MyQRViewController new];
    [self.navigationController  pushViewController:vc animated:YES];
}


#pragma mark  扫描二维码获取红包--=========================================
- (void)getRedenveByQRCode:(NSString *)codeName{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"getRedenveByQRCode" forKey:@"method"];
    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_userId] forKey:@"userId"];
    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_password] forKey:@"password"];
//    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_onlineKey] forKey:@"onlineKey"];
    [dic setObject:codeName forKey:@"name"];
    self.shareApi.delegate=self;
//    [self.shareApi  requestOperationWithDic:dic withPath:SX_Home_POSTCommitBaseUrl withHttpType:@"POST" withTag:SX_getRedenveByQRCodeTag];
}
#pragma mark  扫描二维码获取代金券--=========================================
- (void)getCouponByQRCode:(NSString *)codeName{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"getCouponByQRCode" forKey:@"method"];
    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_userId] forKey:@"userId"];
    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_password] forKey:@"password"];
//    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_onlineKey] forKey:@"onlineKey"];
    [dic setObject:codeName forKey:@"name"];
    self.shareApi.delegate=self;
//    [self.shareApi  requestOperationWithDic:dic withPath:SX_Home_POSTCommitBaseUrl withHttpType:@"POST" withTag:SX_getCouponByQRCodeTag];
}
#pragma mark  扫描二维码激活会员卡--=========================================
- (void)getMemberCardByQRCode:(NSString *)codeName{
    [self dismissViewControllerAnimated:YES completion:^{
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MyInfoStoryboard" bundle:nil];
//        MyCarInfoListViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"MyCarInfoListView"];
//        page.choseCar = @"1";
//        page.codeName = codeName;
//        [self.navigationController   pushViewController:page animated:YES];
    }];
    

}
#pragma   mark  ======================================
#pragma   mark GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
//    if (tag == SX_getRedenveByQRCodeTag){
//        if (  [[database valueForKey:@"respcode"] integerValue]!=1 ) {
//            
//            [self dismissViewControllerAnimated:YES completion:^{
//                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
//            }];
//            
//        }else{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self dismissViewControllerAnimated:YES completion:^{
//                    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MyInfoStoryboard" bundle:nil];
//                    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"RedPacketList"];
//                    [self.navigationController   pushViewController:page animated:YES completion:^{
//                        [[CWHUDTips sharedInstance]  showTips:@"获取红包成功"];
//                    }];
//                }];
//            });
//            
//        }
//    }else if (tag == SX_getCouponByQRCodeTag){
//        if (  [[database valueForKey:@"respcode"] integerValue]!=1 ) {
//            
//            [self dismissViewControllerAnimated:YES completion:^{
//                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
//            }];
//            
//        }else{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self dismissViewControllerAnimated:YES completion:^{
//                    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"MyInfoStoryboard" bundle:nil];
//                    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"KimsVolumeList"];
//                    [self.navigationController   pushViewController:page animated:YES completion:^{
//                        [[CWHUDTips sharedInstance]  showTips:@"获取代金卷成功"];
//                    }];
//                }];
//            });
//            
//        }
//
//    }else if (tag == SX_getMemberCardByQRCodeTag){
//        if (  [[database valueForKey:@"respcode"] integerValue]!=1 ) {
//            
//            [self dismissViewControllerAnimated:YES completion:^{
//                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"respmessage"]  withStatus:1 dismissAfter:1.5];
//            }];
//            
//        }else{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self dismissViewControllerAnimated:YES completion:^{
//                    [[CWHUDTips sharedInstance]  showTips:@"会员卡激活成功"];
//                }];
//            });
//            
//        }
//
//    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    
    
}
@end
